package com.lxg.controller;

import com.lxg.shibie.Token;
import com.lxg.utils.Base64Util;
import com.lxg.utils.FileUtil;
import com.lxg.utils.HttpUtil;
import okhttp3.MediaType;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;
import org.json.JSONArray;
import org.json.JSONObject;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;

import java.io.IOException;
import java.net.URLEncoder;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.util.Base64;

/**
 * @auther xiaolin
 * @creatr 2023/3/20 22:01
 */

@Controller
public class TestController {


//    String url = "https://aip.baidubce.com/rest/2.0/ocr/v1/general_basic";//基础图识别文字

    String url = "https://aip.baidubce.com/rest/2.0/ocr/v1/accurate_basic";//高精度



    static final OkHttpClient HTTP_CLIENT = new OkHttpClient().newBuilder().build();


    @GetMapping("/speech")
    public String toSpeech(){
        return "speech";
    }

    @GetMapping("/form")
    public String getForm(){
        return "form";
    }

    @GetMapping("/speech2")
    public String toSpeech2(){
        return "speech2";
    }

    @GetMapping("/speech3")
    public String toSpeech3(){
        return "speech3";
    }


    @ResponseBody
    @PostMapping("/test3")
    public String speech(String myUrl,String size,String myData,String dataSize) throws IOException {
        MediaType mediaType = MediaType.parse("application/json");
//        String filePath = "src/main/resources/static/test.mp3";
        // speech 可以通过 getFileContentAsBase64("C:\fakepath\7d7adb27-98ab-40f1-a8a6-65732924d7c5.mp3") 方法获取,如果Content-Type是application/x-www-form-urlencoded时,使用getFileContentAsBase64Urlencoded方法获取

//        byte[] b = Files.readAllBytes(Paths.get(filePath));
//        String base64 = Base64.getEncoder().encodeToString(b);
//        System.out.println(b.length);

//        String base64 = myData.substring(23,myData.length());
//        int size = Integer.parseInt(dataSize);
//        System.out.println(base64);
//        System.out.println(size);


        String base64 = myUrl.substring(22,myUrl.length());
        System.out.println(base64);
        System.out.println(size);
        String token = Token.getToken("k148GcjMPDVwLdl5ABIULcxB","ER9rsQfoYN2hb2vCnzxrQCqE6vf2FoSv");

        okhttp3.RequestBody body = okhttp3.RequestBody.create(mediaType, "{\"format\":\"m4a\",\"rate\":16000,\"channel\":1,\"cuid\":\"1\",\"dev_pid\":80001,\"speech\":\""+base64+"\",\"len\":"+size+",\"token\":\"" + token + "\"}");
        Request request = new Request.Builder()
                .url("https://vop.baidu.com/pro_api")
                .method("POST", body)
                .addHeader("Content-Type", "application/json")
                .addHeader("Accept", "application/json")
                .build();

        Response response = HTTP_CLIENT.newCall(request).execute();


        JSONObject json = new JSONObject(response.body().string());//将字符串重新转JSON

        System.out.println(json);

        JSONArray str = json.getJSONArray("result");//识别都内容都放在键为result的数组中
        String result = "";

        for(int i = 0;i<str.length();i++) {//遍历
            result+=str.get(i);//必须进行强转，因为str1.get(i)返回的是Object对象，是最顶层的父类。get("words")只返回value值
        }
        System.out.print(result);
        return result;
    }


    @ResponseBody
    @PostMapping("/test4")
    public String speech2(String myData,String dataSize) throws IOException {
        MediaType mediaType = MediaType.parse("application/json");
//        String filePath = "src/main/resources/static/test.mp3";
        // speech 可以通过 getFileContentAsBase64("C:\fakepath\7d7adb27-98ab-40f1-a8a6-65732924d7c5.mp3") 方法获取,如果Content-Type是application/x-www-form-urlencoded时,使用getFileContentAsBase64Urlencoded方法获取

//        byte[] b = Files.readAllBytes(Paths.get(filePath));
//        String base64 = Base64.getEncoder().encodeToString(b);
//        System.out.println(b.length);

        System.out.println(myData);

        String base64 = myData.substring(22,myData.length());
        int size = Integer.parseInt(dataSize);
//        System.out.println(base64);
        System.out.println(size);


        String token = Token.getToken("k148GcjMPDVwLdl5ABIULcxB","ER9rsQfoYN2hb2vCnzxrQCqE6vf2FoSv");

        okhttp3.RequestBody body = okhttp3.RequestBody.create(mediaType, "{\"format\":\"wav\",\"rate\":16000,\"channel\":1,\"cuid\":\"1\",\"dev_pid\":80001,\"speech\":\""+base64+"\",\"len\":"+size+",\"token\":\"" + token + "\"}");
        Request request = new Request.Builder()
                .url("https://vop.baidu.com/pro_api")
                .method("POST", body)
                .addHeader("Content-Type", "application/json")
                .addHeader("Accept", "application/json")
                .build();

        Response response = HTTP_CLIENT.newCall(request).execute();


        JSONObject json = new JSONObject(response.body().string());//将字符串重新转JSON

        System.out.println(json);

        JSONArray str = json.getJSONArray("result");//识别都内容都放在键为result的数组中
        String result = "";

        for(int i = 0;i<str.length();i++) {//遍历
            result+=str.get(i);//必须进行强转，因为str1.get(i)返回的是Object对象，是最顶层的父类。get("words")只返回value值
        }
        System.out.print(result);
        return result;
    }




    //直接返回测试图片识别的文字
    @ResponseBody
    @GetMapping("/test")
    public String general() {
        try {

            // 编译后，文件根路径
//            URL url1 = General.class.getResource("/test.jpg");

            // 本地文件路径
            String filePath = "src/main/resources/static/img/test2.jpg";

            byte[] imgData = FileUtil.readFileByBytes(filePath);
            String imgStr = Base64Util.encode(imgData);
            String imgParam = URLEncoder.encode(imgStr, "UTF-8");

            String param = "image=" + imgParam;

            // 注意这里仅为了简化编码每一次请求都去获取access_token，线上环境access_token有过期时间， 客户端可自行缓存，过期后重新获取。
            String accessToken = Token.getToken("lWwaEtuBTqFVt0P6KyFC9YCG","zxSxW17DDAK7l2u1PLGSiTgsMjyxa5Zb");


            String result = HttpUtil.post(url, accessToken, param);

            JSONObject json = new JSONObject(result);//将字符串重新转JSON
            JSONArray str = json.getJSONArray("words_result");//识别都内容都放在键为words_result的数组中
            String result0 = "";
            for(int i = 0;i<str.length();i++) {//遍历
                result0+=((JSONObject)str.get(i)).get("words")+"\n";//必须进行强转，因为str1.get(i)返回的是Object对象，是最顶层的父类。get("words")只返回value值
            }
            return result0;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }



}
